const fs = require('fs');

const geojson = JSON.parse(fs.readFileSync('china-county.json', 'utf8'));

function getCenter(coords) {
    try {
        if (!coords) return null;
        if (Array.isArray(coords[0][0][0])) {
            // MultiPolygon
            return coords[0][0][0];
        } else if (Array.isArray(coords[0][0])) {
            // Polygon
            return coords[0][0];
        } else if (Array.isArray(coords[0])) {
            // 只有一个点
            return coords[0];
        }
        return null;
    } catch (e) {
        return null;
    }
}

const cityCoords = {};

geojson.features.forEach(feature => {
    const props = feature.properties;
    const province = props.provinceName || props.province || '';
    const city = props.cityName || props.city || '';
    const district = props.adcodeName || props.name || '';
    const coords = feature.geometry.coordinates;
    const center = getCenter(coords);
    if (!center || center.length < 2) return;
    const [lng, lat] = center;
    const key = `${province}-${city}-${district}`;
    cityCoords[key] = { lng, lat };
});

fs.writeFileSync('cityCoords.json', JSON.stringify(cityCoords, null, 2));
console.log('cityCoords.json 生成完毕');